package com.servlet.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.servlet.bean.User;
import com.servlet.utils.ResponseVo;
import com.servlet.utils.ServletUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Title: UserServlet
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/22 13:44
 */
@WebServlet("/users")
public class UserServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 解决跨域 Access-Control-Allow-Origin
            // 获取请求头信息
            String  origin = req.getHeader("Origin");
            // resp.setHeader("Access-Control-Allow-Origin","http://127.0.0.1:5501");
            resp.setHeader("Access-Control-Allow-Origin",origin);
            req.setCharacterEncoding("utf-8");
            // 创建用户
            List<User> users = Arrays.asList(
                    new User("小明","123456",new Date()),
                    new User("小红","123456",new Date()),
                    new User("寒梅","123456",new Date())
            );
            // System.out.println(1/0);
            ResponseVo<List<User>> responseVo =  ResponseVo.ok("获取用户信息成功",users);
            ServletUtils.writeResponse(resp,responseVo);
        }catch (Exception e) {
            ResponseVo responseVo =  ResponseVo.error("系统异常"+e.toString());
            ServletUtils.writeResponse(resp,responseVo);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
    }
}
